package com.tbl.modules.wms.controller.baseinfo;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.tbl.common.utils.*;
import com.tbl.modules.platform.constant.LogActionConstant;
import com.tbl.modules.platform.constant.MenuConstant;
import com.tbl.modules.platform.controller.AbstractController;
import com.tbl.modules.platform.entity.system.User;
import com.tbl.modules.platform.service.system.LogService;
import com.tbl.modules.platform.service.system.RoleService;
import com.tbl.modules.platform.util.DeriveExcel;
import com.tbl.modules.wms.constant.Constant;
import com.tbl.modules.wms.entity.baseinfo.FactoryArea;
import com.tbl.modules.wms.entity.baseinfo.Warehouse;
import com.tbl.modules.wms.service.baseinfo.FactoryAreaService;
import com.tbl.modules.wms.service.baseinfo.WarehouseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 仓库列表控制层
 * @author 70486
 */
@Controller
@RequestMapping(value = "/warehouselist")
public class WareHouseController extends AbstractController {

    /**
     * 仓库
     */
    @Autowired
    private WarehouseService warehouseService;
    /**
     * 日志
     */
    @Autowired
    private LogService logService;
    /**
     * 角色
     */
    @Autowired
    private RoleService roleService;
    /**
     * 厂区信息
     */
    @Autowired
    private FactoryAreaService factoryAreaService;

    /**
     * 跳转到仓库列表页面
     * @return ModelAndView
     */
    @RequestMapping(value = "/toList")
    public ModelAndView toList() {
        ModelAndView mv = this.getModelAndView();
        mv.addObject("operationCode", roleService.selectOperationByRoleId(getSessionUser().getRoleId(), MenuConstant.warehouselist));
        mv.setViewName("techbloom/baseinfo/warehouse/warehouse_list");
        return mv;
    }

    /**
     * 获取仓库列表数据
     * @param queryJsonString
     * @return Map<String, Object>
     */
    @RequestMapping(value = "/list.do")
    @ResponseBody
    public Map<String, Object> list(String queryJsonString) {
        Map<String, Object> map = new HashMap<>(4);
        if (!StringUtils.isEmptyString(queryJsonString)) {
            map = JSON.parseObject(queryJsonString);
        }
        PageTbl page = this.getPage();
        PageUtils utils = warehouseService.getPageList(page, map);
        page.setTotalRows(utils.getTotalCount() == 0 ? 1 : utils.getTotalCount());
        //初始化分页对象
        executePageMap(map, page);
        map.put("rows", utils.getList());
        map.put("total", utils.getTotalPage() == 0 ? 1 : utils.getTotalPage());
        return map;
    }

    /**
     * 获取原材料仓库列表数据
     * @param queryJsonString
     * @return Map<String, Object>
     */
    @RequestMapping(value = "/yclList.do")
    @ResponseBody
    public Map<String, Object> yclList(String queryJsonString) {
        Map<String, Object> map = new HashMap<>(4);
        if (!StringUtils.isEmptyString(queryJsonString)) {
            map = JSON.parseObject(queryJsonString);
        }
        PageTbl page = this.getPage();
        PageUtils utils = warehouseService.getYclPageList(page, map);
        page.setTotalRows(utils.getTotalCount() == 0 ? 1 : utils.getTotalCount());
        //初始化分页对象
        executePageMap(map, page);
        map.put("rows", utils.getList());
        map.put("total", utils.getTotalPage() == 0 ? 1 : utils.getTotalPage());
        return map;
    }

    /**
     * 导出仓库档案Excel
     * @param request
     * @param response
     */
    @RequestMapping(value = "/materialExcel", method = RequestMethod.POST)
    @ResponseBody
    public void materialExcel(HttpServletRequest request, HttpServletResponse response) {
        try {
            String sheetName = "仓库" + "(" + DateUtils.getDay() + ")";
            response.setHeader("Content-Type", "application/force-download");
            response.setHeader("Content-Type", "application/vnd.ms-excel");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Expires", "0");
            response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
            response.setHeader("Pragma", "public");
            response.setHeader("Content-disposition", "attachment;filename=" + new String(sheetName.getBytes("gbk"),
                    "ISO8859-1") + ".xls");

            Map<String, String> mapFields = new LinkedHashMap<>();
            String [] excelIndexArray = request.getParameter("queryExportExcelIndex").split(",");

            if (excelIndexArray.length==1&&"".equals(excelIndexArray[0])) {
                mapFields.put("code", "仓库编号");
                mapFields.put("name", "仓库名称");
                mapFields.put("factoryCode","厂区编码");
                mapFields.put("factoryName", "厂区名称");
                mapFields.put("stateStr", "状态");
            }else {
                for (String s : excelIndexArray) {
                    if ("2".equals(s)) {
                        mapFields.put("code", "仓库编号");
                    } else if ("3".equals(s)) {
                        mapFields.put("name", "仓库名称");
                    } else if ("4".equals(s)) {
                        mapFields.put("factoryCode", "厂区编码");
                    } else if ("5".equals(s)) {
                        mapFields.put("factoryName", "厂区名称");
                    } else if ("6".equals(s)) {
                        mapFields.put("stateStr", "状态");
                    }
                }
            }

            DeriveExcel.exportExcel(sheetName, warehouseService.getExcelList(request.getParameter("ids"), request.getParameter("queryName"),
                    request.getParameter("queryCode"),request.getParameter("queryFactoryCode"), null), mapFields, response, "");
            logService.logInsert("仓库导出", LogActionConstant.USER_EXPORT, request);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 不可复用
     * @param ids
     */
    @RequestMapping(value = "/unMltiplexing.do")
    @ResponseBody
    public void unMltiplexing(Long[] ids) {
        Warehouse warehouseEntity = new Warehouse();
        warehouseEntity.setRepeatOccupancy(Constant.INT_ZERO);
        warehouseService.update(warehouseEntity, new EntityWrapper<Warehouse>().in("ID", ids));
    }

    /**
     * 可复用
     * @param ids
     */
    @RequestMapping(value = "/mltiplexing.do")
    @ResponseBody
    public void mltiplexing(Long[] ids) {
        Warehouse warehouseEntity = new Warehouse();
        warehouseEntity.setRepeatOccupancy(Constant.INT_ONE);
        warehouseService.update(warehouseEntity, new EntityWrapper<Warehouse>().in("ID", ids));
    }

    /**
     * 禁用
     * @param ids
     */
    @RequestMapping(value = "/disMiss.do")
    @ResponseBody
    public void disMiss(Long[] ids) {
        Warehouse warehouseEntity = new Warehouse();
        warehouseEntity.setState(Constant.INT_ZERO);
        warehouseService.update(warehouseEntity, new EntityWrapper<Warehouse>().in("ID", ids));
    }

    /**
     * 启用
     * @param ids
     */
    @RequestMapping(value = "/isStart.do")
    @ResponseBody
    public void isStart(Long[] ids) {
        Warehouse warehouseEntity = new Warehouse();
        warehouseEntity.setState(Constant.INT_ONE);
        warehouseService.update(warehouseEntity, new EntityWrapper<Warehouse>().in("ID", ids));
    }

    /**
     * 根据厂区编码获取第一个仓库
     * @param factoryCode 厂区编码
     * @return Warehouse 仓库
     */
    @RequestMapping(value = "/getFirstWarehouse.do")
    @ResponseBody
    public Warehouse getFirstWarehouse(String factoryCode){
        Warehouse returnWarehouse = null;
        if(StringUtils.isNotEmpty(factoryCode)) {
            List<Warehouse> warehouseList = warehouseService.selectList(new EntityWrapper<Warehouse>()
                    .eq("FACTORYCODE", factoryAreaService.selectOne(new EntityWrapper<FactoryArea>()
                            .eq("CODE", factoryCode)).getCode())
                    .eq("STATE", 1));
            if(warehouseList.size()>0) {
                returnWarehouse = warehouseList.get(0);
                returnWarehouse.setWarehouseCodeName(returnWarehouse.getCode()+"_"+returnWarehouse.getName());
            }
        }
        return returnWarehouse;
    }

    /**
     * 根据仓库获取仓库
     * @param id 仓库主键
     * @return Warehouse 仓库
     */
    @RequestMapping(value = "/findWareByWare.do")
    @ResponseBody
    public Warehouse findWareByWare(String id){
        Warehouse returnWarehouse = warehouseService.selectById(id);
        returnWarehouse.setWarehouseCodeName(returnWarehouse.getCode()+"_"+returnWarehouse.getName());

        return returnWarehouse;
    }

    /**
     * 当前用户的仓库
     * @return Warehouse 仓库
     */
    @RequestMapping(value = "/findWareByUser")
    @ResponseBody
    public Map<String,Object> findWareByUser(){
        EntityWrapper ew = new EntityWrapper<Warehouse>();
        String ur = super.getSessionUser().getUserWarehouseIds();
        Map<String, Object> map = new HashMap<>();
        if (ur != null) {
            ew.in("id", ur.split(","));
            //map.put("data", warehouseService.selectList(ew));
            String area="",entity="";
            for(Warehouse item : (List<Warehouse>)warehouseService.selectList(ew)){
                area += item.getFactoryCode()+"_"+item.getCode()+",";
                entity += item.getEntityId()+"_"+item.getCode()+",";
            }
            map.put("area", area);
            map.put("entity", entity);
        }
        return map;
    }
    /**
     * 同步仓库基础数据
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/synchronousdata.do")
    @ResponseBody
    public Map<String,Object> synchronousdata() {
        //下面代码不能删除
        /*try {
            logger.info(DateUtils.getTime()+" >>同步仓库基础数据....");
            Map<String, Object> xmlMap = new HashMap<>(1);
            xmlMap.put("line", new HashMap<String, Object>(2) {{
                put("plantcode", "");
                put("warehouseno", "");
                put("warehousename", "");
            }});
            wmsService.FEWMS013(xmlMap);
        } catch (Exception e) {
            e.printStackTrace();
        }*/

        Connection conn = JDBCUtils.getConnection();
        PreparedStatement pst = null;
        // 创建执行存储过程的对象
        CallableStatement proc = null;
        try {
            proc = conn.prepareCall("{ call EBS2WMS_YDDL_WAREHOUSE () }");
            // 执行
            proc.execute();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭IO流
                proc.close();
                JDBCUtils.closeAll(null, pst, conn);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return new HashMap<String,Object>(2) {{
            put("result", true);
            put("msg", "更新成功！");
        }};
    }

    /**
     * 获取厂区对应仓库的下拉选信息
     * @param factoryCode 厂区编码
     * @param queryString 查询条件
     * @param pageSize 每页大小
     * @param pageNo 页码
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/getWarehouseByFactory")
    @ResponseBody
    public Map<String, Object> getWarehouseByFactory(String factoryCode,String queryString,int pageSize,int pageNo) {
        Map<String, Object> map = new HashMap<>();
        PageTbl page = this.getPage();
        page.setPageno(pageNo);
        page.setPagesize(pageSize);
        //okk
        map.put("factoryCodeList", getSessionUser().getFactoryCode()!=null?Arrays.asList(getSessionUser().getFactoryCode().split(",")):null);
        map.put("warehouseIds", getSessionUser().getUserWarehouseIds()!=null?Arrays.asList(getSessionUser().getUserWarehouseIds().split(",")):null);
        map.put("factoryId", factoryCode);
        map.put("queryString", queryString.toUpperCase());
        PageUtils utils = warehouseService.getPageWarehouseList(page, map);
        page.setTotalRows(utils.getTotalCount() == 0 ? 1 : utils.getTotalCount());
        //初始化分页对象
        executePageMap(map, page);
        map.put("result", utils.getList());
        map.put("total", utils.getTotalCount() == 0 ? 1 : utils.getTotalCount());
        return map;
    }

    /**
     * 根据主键查询仓库
     * @param id 仓库主键
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/findWarehouseById")
    @ResponseBody
    public Warehouse findWarehouseById(String id) {
        return warehouseService.selectById(id);
    }

    /**
     * 获取仓库列表信息 ：下拉框
     * @param queryString 查询条件
     * @param pageSize 页大小
     * @param pageNo 页码
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/getWarehouseList")
    @ResponseBody
    public Map<String, Object> getWarehouseList(String queryString, int pageSize, int pageNo) {
        Map<String, Object> map = new HashMap<>();
        PageTbl page = this.getPage();
        map.put("page", pageNo);
        map.put("limit", pageSize);
        String sortOrder = page.getSortorder();
        if (StringUtils.isEmptyString(sortOrder)) {
            sortOrder = "desc";
            page.setSortorder(sortOrder);
        }
        map.put("sidx", page.getSortname());
        map.put("order", page.getSortorder());
        map.put("dname", queryString.toUpperCase());
        //获取仓库列表信息 ：下拉框
        map.put("result", warehouseService.getWarehouseList(map));
        return map;
    }


    /**
     * 获取厂区对应原材料仓库的下拉选信息
     * @param factoryCode
     * @return Map<String, Object>
     */
    @RequestMapping(value = "/getYclWarehouseByFactory")
    @ResponseBody
    public Map<String, Object> getYclWarehouseByFactory(String factoryCode) {
        Map<String, Object> map = new HashMap<>(2);
        map.put("factoryId", factoryCode);
        map.put("warehouseIds", getSessionUser().getUserWarehouseIds()!=null?Arrays.asList(getSessionUser().getUserWarehouseIds().split(",")):null);
        Map<String, Object> resultMap = new HashMap<>(3);
        List<Map<String, Object>> list = warehouseService.getYclPageWarehouseList(map);
        if(list!=null && !list.isEmpty()){
            resultMap.put("data", list);
            resultMap.put("msg","success");
            resultMap.put("result",true);
        }else{
            resultMap.put("msg","not data");
            resultMap.put("result",false);
        }
        return resultMap;

    }

    /**
     * 获取厂区对应原材料仓库的下拉选信息
     * @param entityId
     * @return Map<String, Object>
     */
    @RequestMapping(value = "/getYclWarehouseByEntityId")
    @ResponseBody
    public Map<String, Object> getYclWarehouseByEntityId(String entityId) {
        Map<String, Object> map = new HashMap<>(2);
        map.put("entityId", entityId);
        Map<String, Object> resultMap = new HashMap<>(3);
        List<Map<String, Object>> list = warehouseService.getYclPageWarehouseListByEntityID(map);
        if(list!=null && !list.isEmpty()){
            resultMap.put("data", list);
            resultMap.put("msg","success");
            resultMap.put("result",true);
        }else{
            resultMap.put("msg","not data");
            resultMap.put("result",false);
        }
        return resultMap;

    }

}
